package com.lovo.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.common.bean.UserInfoBean;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.ResponseResult;
import com.lovo.common.result.ResultCode;
import com.lovo.common.util.JWTUtil;
import com.lovo.common.util.MQUtil;
import com.lovo.user.service.IUserInfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/users")
@ResponseResult
public class UserInfoController {
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private MQUtil mqUtil;
    @PostMapping("/login")
    public Object login(String userName,String userPass) throws GlobalHandleException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        queryWrapper.eq("user_pass", DigestUtils.sha256Hex(userPass));
        UserInfoBean userInfoBean = userInfoService.getOne(queryWrapper);
        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }else{
            return JWTUtil.createToken(userName,userInfoBean.getUserPass());
        }
    }
    @PostMapping("/register")
    public Object register(@RequestBody UserInfoBean userInfoBean){
        userInfoService.save(userInfoBean);
        mqUtil.send("shop.direct.exchange","register_direct_rk",userInfoBean);
        return "注册成功";
    }
    @GetMapping("/token")
    public Object getUserWithToken(HttpServletRequest request){
        return SecurityUtils.getSubject().getPrincipal();
    }
}

